package com.jieyun.core.component.page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.jieyun.core.component.page.PagerConfig.PagerProperties;
import com.jieyun.core.exception.GlobalException;
import com.jieyun.core.utils.ServletUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 基础的分页注解处理器
 * @author trekxu
 *
 */
@Component
@Aspect
@Slf4j
public class PageHandlerAspect {

	@Resource
	private PagerProperties pagerProperties;
	           
	@Pointcut("@annotation(com.jieyun.core.component.page.Page)")
	public void pagePoint() {
	}

	/**
	 * 实现分页
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Around(value = "pagePoint()")
	public Object pageAround(ProceedingJoinPoint jp) throws Throwable {
		HttpServletRequest request = ServletUtils.getRequest();

		// 获取分页参数
		Integer page = getPage(request);
		Integer limit = getLimit(request);

		PageHelper.startPage(page, limit);
		Object result = jp.proceed();

		if (!(result instanceof Pager)) {
			throw new IllegalArgumentException("使用@Page注解的方法返回值必须是Pager");
		}

		Pager pager = (Pager) result;

		Long total = PageHelper.freeTotal();

		pager.setCount(total);
		// 下面包装Pager的内容
		return pager;
	}

	/**
	 * 获取分页页码
	 * 
	 * @param request
	 * @return
	 */
	private Integer getPage(HttpServletRequest request) {
		try {
			return Integer.parseInt(request.getParameter(pagerProperties.getPageName()));
		} catch (NumberFormatException e) {
			log.error("获取分页信息出现问题");
			throw new GlobalException("获取分页信息出现问题");
		}
	}

	/**
	 * 获取分页的大小
	 * 
	 * @param request
	 * @return
	 */
	private Integer getLimit(HttpServletRequest request) {
		try {
			return Integer.parseInt(request.getParameter(pagerProperties.getLimitName()));
		} catch (NumberFormatException e) {
			log.error("获取分页信息出现问题");
			throw new GlobalException("获取分页信息出现问题");
		}
	}
}
